package sg.partying.lcb.android.ui

import android.graphics.Bitmap
import android.graphics.Point
import android.hardware.Camera
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.HandlerThread
import android.util.DisplayMetrics
import android.util.Log
import android.view.PixelCopy
import android.view.SurfaceView
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.blankj.utilcode.util.ScreenUtils
import com.salton123.base.DelegateActivity
import com.salton123.base.ViewBindingActivity
import com.salton123.base.ViewBindingFragment
import com.salton123.base.feature.ImmersionFeature
import com.salton123.camera.CameraV1
import com.salton123.camera.VirtualBackgroundRenderView
import com.salton123.utils.BitmapUtil
import com.salton123.utils.PreferencesUtils
import kt.runOnUi
import kt.singleClick
import kt.toast
import sg.partying.lcb.android.Prop
import sg.partying.lcb.android.R
import sg.partying.lcb.android.Session
import sg.partying.lcb.android.databinding.FragmentTakePhotoBinding


/**
 * Time:2022/1/29 11:40 上午
 * Author:
 * Description:
 */
class TakePhotoActivity : DelegateActivity() {
    override fun getLayout(): Int = R.layout.fragment_take_photo
    override fun initVariable(savedInstanceState: Bundle?) {
        ImmersionFeature(this).onBind()
    }

    private var mCamera: CameraV1? = null
    private var mCameraId = 0
    private var countDownTimer: CountDownTimer? = null
    private var index = 0
    private lateinit var virtualView: VirtualBackgroundRenderView
    private lateinit var imageView: ImageView
    private lateinit var imageViewCloud: ImageView
    private lateinit var tvStart: TextView
    private lateinit var flRetengle: FrameLayout
    override fun initViewAndData() {
        virtualView = f(R.id.virtualView)
        imageView = f(R.id.imageView)
        imageViewCloud = f(R.id.imageViewCloud)
        tvStart = f(R.id.tvStart)
        flRetengle = f(R.id.flRetengle)
        val windowSize = Point()
        activity().windowManager.defaultDisplay.getSize(windowSize)
        setViewHeight(virtualView, windowSize.y)
        initGLSurfaceView()
        index = intent?.getIntExtra("index", 0) ?: 0
        when (index) {
            0 -> {
                imageView.setImageResource(com.salton123.resources.R.drawable.bg_take_photo_virtual_01)
                imageViewCloud.setImageResource(com.salton123.resources.R.drawable.bg_take_photo_cloud_01)
                virtualView.setBackgroundImage(com.salton123.resources.R.drawable.bg_take_photo_virtual_01)
            }

            1 -> {
                imageView.setImageResource(com.salton123.resources.R.drawable.bg_take_photo_virtual_02)
                imageViewCloud.setImageResource(com.salton123.resources.R.drawable.bg_take_photo_cloud_02)
                virtualView.setBackgroundImage(com.salton123.resources.R.drawable.bg_take_photo_virtual_02)
            }

            2 -> {
                imageView.setImageResource(com.salton123.resources.R.drawable.bg_take_photo_virtual_03)
                imageViewCloud.setImageResource(com.salton123.resources.R.drawable.bg_take_photo_cloud_03)
                virtualView.setBackgroundImage(com.salton123.resources.R.drawable.bg_take_photo_virtual_03)
            }
        }

        tvStart.singleClick {
            countDownTimer = object : CountDownTimer(5 * 1000, 1 * 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    Log.e("NB", "剩余时间$millisUntilFinished")
                    tvStart.text = "${(millisUntilFinished / 1000).toInt()}"
                }

                override fun onFinish() {
                    flRetengle.visibility = View.GONE
                    virtualView.apply {
                        usePixelCopy(this) {
                            virtualView.runOnUi {
                                imageView.setImageBitmap(it)
                                virtualView.visibility = View.GONE
                            }
                            val target = ScreenUtils.screenShot(activity())
                            val result = BitmapUtil.saveImage(Prop.qrCodeTempSavePath, target, Bitmap.CompressFormat.JPEG, 80)
                            toast("save image:$result")
                            if (result) {
                                openActivity(QrCodeActivity::class.java, Bundle())
                                finish()
                            } else {
                                restart()
                            }
                        }
                    }
                }
            }
            countDownTimer?.start()
        }
    }

    fun restart() {
        tvStart.setText(com.salton123.translate.R.string.start)
        flRetengle.visibility = View.VISIBLE
    }

    /**
     * Pixel copy to copy SurfaceView/VideoView into BitMap
     */
    fun usePixelCopy(videoView: SurfaceView, callback: (Bitmap?) -> Unit) {
        val bitmap: Bitmap = Bitmap.createBitmap(
            videoView.width,
            videoView.height,
            Bitmap.Config.ARGB_8888
        );
        try {
            // Create a handler thread to offload the processing of the image.
            val handlerThread = HandlerThread("PixelCopier");
            handlerThread.start();
            PixelCopy.request(
                videoView, bitmap,
                { copyResult ->
                    if (copyResult == PixelCopy.SUCCESS) {
                        callback(bitmap)
                    }
                    handlerThread.quitSafely();
                },
                Handler(handlerThread.looper)
            )
        } catch (e: IllegalArgumentException) {
            callback(null)
            // PixelCopy may throw IllegalArgumentException, make sure to handle it
            e.printStackTrace()
        }
    }

    private fun initGLSurfaceView() {
        mCameraId = if (PreferencesUtils.getBoolean("isFront")) {
            Camera.CameraInfo.CAMERA_FACING_FRONT
        } else {
            Camera.CameraInfo.CAMERA_FACING_BACK
        }
        val dm = DisplayMetrics()
        mCamera = CameraV1(activity())
        if (!mCamera!!.openCamera(dm.widthPixels, dm.heightPixels, mCameraId)) {
            return
        }
        virtualView.setRenderer(activity(), mCamera, false)
    }

    fun setViewHeight(view: View, nHeight: Int) {
        val lp = view.layoutParams as FrameLayout.LayoutParams
        lp.height = nHeight
        view.layoutParams = lp
    }


    override fun onPause() {
        super.onPause()
        virtualView.onPause()
        mCamera?.stopPreview()
    }

    override fun onResume() {
        super.onResume()
        virtualView.onResume()
        mCamera?.startPreview()
    }

    override fun onDestroy() {
        super.onDestroy()
        virtualView.onPause()
        virtualView.deinit()
        mCamera?.stopPreview()
        mCamera?.releaseCamera()
        mCamera = null
        countDownTimer?.cancel()
        countDownTimer = null
    }


}
